package com.compty.security.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.compty.core.struts2.BaseAction;
import com.compty.paint.domain.AddressInfo;
import com.compty.paint.domain.CityInfo;
import com.compty.paint.domain.CustomerInfo;
import com.compty.paint.domain.ProvinceInfo;
import com.compty.paint.manager.AddressInfoManager;
import com.compty.paint.manager.CityInfoManager;
import com.compty.paint.manager.CustomerInfoManager;
import com.compty.paint.manager.ProvinceInfoManager;
import com.compty.paint.manager.UserStateManager;
import com.compty.paint.util.Constants;
import com.compty.security.domain.Role;
import com.compty.security.domain.User;
import com.compty.security.domain.UserState;
import com.compty.security.manager.RoleManager;
import com.compty.security.manager.UserManager;


/**
 * user action.
 *
 */
public class UserAction extends BaseAction<User> {
    /** * serial. */
    static final long serialVersionUID = 0L;

    /** logger. */
    private static Logger logger = LoggerFactory.getLogger(UserAction.class);

    /** * user manager. */
    private transient UserManager userManager = null;
    private transient CustomerInfoManager customerInfoManager = null;
	private transient AddressInfoManager  addressInfoManager = null;
	private transient ProvinceInfoManager provinceInfoManager = null;
	private transient CityInfoManager cityInfoManager = null;
    
    private UserStateManager userStateManager = null;

    /** * role manager. */
    private transient RoleManager roleManager = null;

    /** * user list. */
    private List<User> list;

    /** * role list. */
    private List<Role> roleList;

    /** * id. */
    private long id;
    
    private String operateStr;//用户状态修改，1表示通过，2表示不通过，3表示删除

    /** * message. */
    private String message;

    // ====================================================
    private String ids;
    private Long userId;
    private Long roleId;
    private boolean auth;
    private User userInfo;
    private Date startDate;
	private Date endDate;

    /** *列出所有管理员账户. */
	public String list() {
    	String hql = " from User where administratorFlag= ?";
        this.list = userManager.find(hql,new String[]{"1"});
        return SUCCESS;
    }
	
	/**
	 *@Todo:修改管理员及商户状态
	 *@author:zhuqh
	 *@CreateTime:2011-6-9 上午10:19:17
	 */
	public String changeState(){
		
		if(userId != null){
			User user = userManager.get(userId);
			
			if("1".equals(operateStr)){
				UserState  userState = userStateManager.findUniqueBy("english_name", Constants.User_State_Normal);
				user.setUserState(userState);
				userManager.save(user);
			}else if("2".equals(operateStr)){
				UserState  userState = userStateManager.findUniqueBy("english_name", Constants.User_State_Overrule);
				user.setUserState(userState);
				userManager.save(user);
			}
			else if("3".equals(operateStr)){//删除
				 userManager.removeById(userId);
//				UserState  userState = userStateManager.findUniqueBy("english_name", Constants.User_State_hidden);
//				user.setUserState(userState);
//				userManager.save(user);
			}
		}
		
		return "listMember";
	}
	
	/**
	 *@Todo:修改管理员及商户上传状态
	 */
	public String changeState_customer(){
		
		if(userId != null){
			CustomerInfo customerInfo = customerInfoManager.get(userId);
			
			if("1".equals(operateStr)){
				UserState  userState = userStateManager.findUniqueBy("english_name", Constants.User_State_Normal);
				customerInfo.setUserState(userState);
				customerInfoManager.save(customerInfo);
			}else if("2".equals(operateStr)){
				UserState  userState = userStateManager.findUniqueBy("english_name", Constants.User_State_Overrule);
				customerInfo.setUserState(userState);
				customerInfoManager.save(customerInfo);
			}
			else if("3".equals(operateStr)){//删除
				customerInfoManager.removeById(userId);
			}
		}
		
		return "listCustomer";
	}
	
	/**
	 * 列出会员所有收货地址
	 */
	@SuppressWarnings("unchecked")
	public String listAddressOfCustomer(){
		
		String id = request.getParameter("id");
		Long cId = Long.valueOf(id);
		
		CustomerInfo customerInfo = customerInfoManager.get(cId);
		List<AddressInfo>  addressList = addressInfoManager.findByCustomerInfo(customerInfo);
		
		List<Map> returnList = new ArrayList<Map>();
		for (int i = 0; i < addressList.size(); i++) {
			AddressInfo addressInfoItem = addressList.get(i);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("id", addressInfoItem.getId());
			map.put("consignee", addressInfoItem.getConsignee());
			map.put("mobile", addressInfoItem.getMobile());
			map.put("zipCode", addressInfoItem.getZipCode());
			if( addressInfoItem.getProvinceInfo() != null){
				ProvinceInfo provinceInfo = provinceInfoManager.get(addressInfoItem.getProvinceInfo().getId());
				map.put("provinceInfo", provinceInfo.getName());
			}
			if( addressInfoItem.getCityInfo() != null){
				CityInfo cityInfo = cityInfoManager.get(addressInfoItem.getCityInfo().getId());
				map.put("cityInfo", cityInfo.getName());
			}
			map.put("address", addressInfoItem.getAddress());
			returnList.add(map);
		}
		String  addressArray = JSONArray.fromObject(returnList).toString();
		request.setAttribute("ajaxData",addressArray);
		
		return "listAddressOfCustomer";
	}
	
    /** * @return forward. */
    public String edit() {
        this.userInfo = userManager.get(id);

        return "forward";
    }

    /** * @return rolesByUser. */
    public String rolesByUser() {
        this.entity = userManager.get(id);
        this.roleList = roleManager.getAll();

        for (Role role : roleList) {
            if (entity.getRoles().contains(role)) {
                role.setAuthorized(true);
            }
        }

        return "rolesByUser";
    }

    /** * @return auth end. */
    public String auth() {
        User user = userManager.get(id);
        Role role = roleManager.get(roleId);

        if (!user.getRoles().contains(role)) {
            user.getRoles().add(role);
            userManager.save(user);
        }

        return "auth-end";
    }

    /** * @return auth end. */
    public String unauth() {
        User user = userManager.get(id);
        Role role = roleManager.get(roleId);

        if (user.getRoles().contains(role)) {
            user.getRoles().remove(role);
            userManager.save(user);
        }

        return "auth-end";
    }

    //
    /** * @param userManager user manager. */
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    /** * @param roleManager role manager. */
    public void setRoleManager(RoleManager roleManager) {
        this.roleManager = roleManager;
    }

    /** * @return user list. */
    public List<User> getList() {
        return list;
    }

    /** * @return role list. */
    public List<Role> getRoleList() {
        return roleList;
    }

    /** * @param id long. */
    public void setId(long id) {
        this.id = id;
    }

    /** * @param roleId long. */
    public void setRoleId(long roleId) {
        this.roleId = roleId;
    }

    /** * @return message. */
    public String getMessage() {
        return message;
    }


    /**
     * 分页列出商户会员.
     *
     * @throws Exception 异常
     */
    public String listMember() throws Exception {

        Criteria criteria;

        if (sort != null) {
            boolean isAsc = dir.equalsIgnoreCase("asc");
            criteria = userManager.createCriteria(sort, isAsc);
        } else {
            criteria = userManager.createCriteria();
        }
        criteria.addOrder(Order.desc("id"));

        if ((filterTxt != null) && (filterValue != null)&& (!filterTxt.equals("")) && (!filterValue.equals(""))) {
            criteria = criteria.add(Restrictions.like(filterTxt,
                        "%" + filterValue + "%"));
        }
        
       if(startDate != null){
       	 criteria = criteria.add(Restrictions.ge("registerTime", startDate));
       }
       
       if(endDate != null){
       	 criteria = criteria.add(Restrictions.lt("registerTime", endDate));
       }
        
        criteria = criteria.add(Restrictions.eq("administratorFlag", "0"));//为会员，非管理员

        this.page = userManager.pagedQuery(criteria, curPage, pageSize);
        
        return "member_list";
    }
    
    /**
     * 列出会员
     * @throws Exception
     */
    public String listCustomer() throws Exception {

        Criteria criteria;

        if (sort != null) {
            boolean isAsc = dir.equalsIgnoreCase("asc");
            criteria = customerInfoManager.createCriteria(sort, isAsc);
        } else {
            criteria = customerInfoManager.createCriteria();
        }
        criteria.addOrder(Order.desc("id"));

        if ((filterTxt != null) && (filterValue != null)&& (!filterTxt.equals("")) && (!filterValue.equals(""))) {
            criteria = criteria.add(Restrictions.like(filterTxt,
                        "%" + filterValue + "%"));
        }
        
       if(startDate != null){
       	 criteria = criteria.add(Restrictions.ge("registerTime", startDate));
       }
       
       if(endDate != null){
       	 criteria = criteria.add(Restrictions.lt("registerTime", endDate));
       }

        this.page = customerInfoManager.pagedQuery(criteria, curPage, pageSize);
        
        return "customer_list";
    }

    /**
     * 使用json绑定pojo，再将绑定的pojo返回.
     * @return T entity
     * @throws Exception 解析时，可能抛出异常
    
    protected User bindObject() throws Exception {
        User user = null;

        try {
            user = userManager.get(entity.getId());
        } catch (JSONException ex) {
            System.err.println(ex);
        }

        if (user == null) {
            if (userManager.findBy("username", entity.getUsername()).size() > 0) {
                throw new Exception("User already exists.");
            }

            user = entity;
            logger.info("{}", user);
            logger.info("{}", passwordEncoder);
            user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
        } else {
            MainUtils.copy(entity, user);
        }

        return user;
    } */

    /**
     * 保存，新增或修改.
     *
     * @throws Exception 异常
     */
    public String save() throws Exception {
//        User entity = bindObject();
    	if(this.userInfo != null){
    		User  user = userManager.get(userInfo.getId());
    		
    		user.setUsername(userInfo.getUsername());
    		user.setMobile(userInfo.getMobile());
    		user.setTelphone(userInfo.getTelphone());
    		user.setEmailAddress(userInfo.getEmailAddress());
    		user.setAddress(userInfo.getAddress());
    		
    		userManager.save(user);
    	}
    	return "redirect";
    }

    /**
     * 读取数据.
     *
     * @throws Exception 异常
     */
    public void loadData() throws Exception {
        User entity = userManager.get(id);

        if (entity != null) {
            List<User> list = new ArrayList<User>();
            list.add(entity);
        }
    }

    /**
     * 删除记录.
     *
     * @throws Exception 异常
     */
    public String remove() throws Exception {
        for (String str : ids.split(",")) {
            try {
                long id = Long.parseLong(str);
                userManager.removeById(id);
            } catch (NumberFormatException ex) {
                continue;
            }
        }

        return "redirect";
    }

    public void setIds(String ids) {
        this.ids = ids;
    }

    /**
     * 显示用户对应的角色列表.
     *
     * @throws Exception 异常
     */
    public void getRoles() throws Exception {
        // mv.setViewName("/admin/selectRoles");
        User user = userManager.get(userId);
        List<Role> roles = roleManager.getAll();

        if (user != null) {
            for (Role role : roles) {
                if (user.getRoles().contains(role)) {
                    role.setAuthorized(true);
                }
            }
        }
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public void setAuth(boolean auth) {
        this.auth = auth;
    }
    
    public String getOperateStr() {
		return operateStr;
	}

	public void setOperateStr(String operateStr) {
		this.operateStr = operateStr;
	}

	public void setUserStateManager(UserStateManager userStateManager) {
		this.userStateManager = userStateManager;
	}
	
	public User getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(User userInfo) {
		this.userInfo = userInfo;
	}
	
	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public void setCustomerInfoManager(CustomerInfoManager customerInfoManager) {
		this.customerInfoManager = customerInfoManager;
	}
	
	public void setAddressInfoManager(AddressInfoManager addressInfoManager) {
		this.addressInfoManager = addressInfoManager;
	}
	
	public void setCityInfoManager(CityInfoManager cityInfoManager) {
		this.cityInfoManager = cityInfoManager;
	}
	
	public void setProvinceInfoManager(ProvinceInfoManager provinceInfoManager) {
		this.provinceInfoManager = provinceInfoManager;
	}

	/**
     * 授权与撤消授权.
     *
     * @throws Exception 异常
     */
    public void authRole() throws Exception {
        User user = userManager.get(userId);
        Role role = roleManager.get(roleId);

        if (auth) {
            if (!user.getRoles().contains(role)) {
                user.getRoles().add(role);
            }
        } else {
            if (user.getRoles().contains(role)) {
                user.getRoles().remove(role);
            }
        }

        userManager.save(user);
        ServletActionContext.getResponse().getWriter()
                            .print("{success:true}");
    }
}
